package com.xindaoapp.happypet.fragments;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindao.photonics.fragments.manager.BaseFragment;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.MainActivity;
import com.xindaoapp.happypet.bean.InteralGoodsdesc;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.RollViewPager;

/**
 * 商品详情
 * 
 * @author Administrator
 * 
 */
public class ChangeDescFragment extends BaseFragment {

    private ScheduledExecutorService scheduledExecutor;
    private TextView vMoreNiu, vNiuniu;
    private ListView vChangelist;


    private List<String> imageViewUrlLists;
    private RollViewPager mRollViewPager;
    private ViewPager vViewpager;
    private TextView vTitle, vJinbi, vNum, vIntegral;

    private ArrayList<View> dotLists;
    // 轮播
    private RollViewPager rollViewPager;
    private RelativeLayout viewpager;
    private LinearLayout vViewpage;
    private TextView vDescription;
    private LinearLayout vDotall;

    InteralGoodsdesc goods = null;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_change_desc, container, false);
    }

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        // 牛牛币
        vNiuniu = (TextView) view.findViewById(R.id.niuniubi);
        mRmb = (ImageView) view.findViewById(R.id.rmb);
        showniuniu();
        vViewpager = (ViewPager) view.findViewById(R.id.top_change_viewpager);
        vDotall = (LinearLayout) view.findViewById(R.id.ll_points1);
        vTitle = (TextView) view.findViewById(R.id.title);
        vJinbi = (TextView) view.findViewById(R.id.tv_jinbi);
        vNum = (TextView) view.findViewById(R.id.tv_num);
        vIntegral = (TextView) view.findViewById(R.id.tv_integral);
        webView = (WebView) view.findViewById(R.id.wv);
        webView.getSettings().setDefaultTextEncodingName("UTF-8");

        scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutor.scheduleAtFixedRate(new MyPagerTask(), 2, 3, TimeUnit.SECONDS);
        initdata();

        vViewpager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                currentItem = position;
                int myIndex = position % goods.img_url.size();
                // 将当前指示点的图片enable设为true
                vDotall.getChildAt(myIndex).setEnabled(true);
                // 将上一个指示点设置为false
                vDotall.getChildAt(lastPointIndex).setEnabled(false);
                lastPointIndex = myIndex;

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

        vIntegral.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (UserState.isLogged(getActivity())) {
                    Intent intent = new Intent(mActivity, MainActivity.class);
                    intent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                            ChangeQueRenFragment.class.getCanonicalName());
                    Bundle bundle = new Bundle();
                    bundle.putString("ex_id", getArguments().getString("ex_id"));
                    intent.putExtra(Constants.KEY_BUNDLE, bundle);
                    mActivity.startActivity(intent);
                    mActivity.finish();
                    // startFragment(new ChangeQueRenFragment(), bundle);
                }
            }
        });
    }

    private void showniuniu() {
        if (UserState.getUser() != null) {
            vNiuniu.setText(UserState.getUser().niuniu);
        } else {
            mRmb.setVisibility(View.INVISIBLE);
            vNiuniu.setVisibility(View.INVISIBLE);
        }
    }

    private void initdata() {
        // String exid = "3";
        if (null != getArguments()) {
            String exid = getArguments().getString("ex_id");
            getMoccaApi().getChangeDesc(exid, new IRequest<InteralGoodsdesc>() {

                @Override
                public void request(InteralGoodsdesc t) {
                    if (t != null) {
                        goods = t;
                        webView.loadData(goods.goods_desc, "text/html; charset=UTF-8", null);

                        vViewpager.setAdapter(new MyPagerAdapter(goods.img_url));
                        initDots(goods.img_url.size());
                        vTitle.setText(goods.goods_name);
                        vJinbi.setText(goods.exchange_integral);
                        vNum.setText(goods.goods_number);
                    }
                }

            });
        }

    }

    private void initDots(int size) {
        dotLists = new ArrayList<View>();
        vDotall.removeAllViews();
        for (int i = 0; i < size; i++) {
            // LinearLayout.LayoutParams layoutParams =
            // new LinearLayout.LayoutParams(CommonUtil.dip2px(mActivity, 10),
            // CommonUtil.dip2px(mActivity, 10));
            // layoutParams.setMargins(5, 0, 5, 0);
            // // LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(15,
            // // 15);
            //
            // // lp.leftMargin = 10;
            //
            // View m = new View(mActivity);
            // if (i == 0) {
            // m.setBackgroundResource(R.drawable.point_enable);
            // } else {
            // m.setBackgroundResource(R.drawable.point_normal);
            // }
            // m.setLayoutParams(layoutParams);
            // dotLists.add(m);
            // vDotall.addView(m);

            // 添加指示点
            ImageView point = new ImageView(mActivity);
            point.setBackgroundResource(R.drawable.point_background);
            LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, -2);
            params.leftMargin = 15;
            point.setLayoutParams(params);

            vDotall.addView(point);
            if (i == 0) {
                point.setEnabled(true);
            } else {
                point.setEnabled(false);
            }

        }
    }

    @Override
    protected void initEvents(View view) {
        super.initEvents(view);
    }

    @Override
    protected void initEvents() {
        super.initEvents();
    }

    private final boolean isFirst = true;
    private WebView webView;

    @Override
    protected void onLoadData() {
        super.onLoadData();

    }

    @Override
    protected String getTitleName() {
        return "商品详情";
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public Object getItem(int arg0) {
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            return 0;
        }

        @Override
        public boolean isEnabled(int position) {
            return false;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup arg2) {
            convertView = View.inflate(mActivity, R.layout.item_changecenter, null);
            ImageView img1 = (ImageView) convertView.findViewById(R.id.img1);
            ImageView img2 = (ImageView) convertView.findViewById(R.id.img2);
            img1.setImageResource(R.drawable.all158);
            img2.setImageResource(R.drawable.all292);
            return convertView;
        }

    }


    class MyPagerAdapter extends PagerAdapter {

        List<String> list;

        public MyPagerAdapter(List<String> list) {
            super();
            this.list = list;
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // 获得指定位置的view
            ImageView iv = new ImageView(mActivity);
            iv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.MATCH_PARENT));
            iv.setScaleType(ScaleType.FIT_XY);
            ImageLoader.getInstance().displayImage(list.get(position % list.size()), iv);
            // 将view 添加至container
            container.addView(iv);
            return iv;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

    }


    private int lastPointIndex = 0;
    private int currentItem;

    private class MyPagerTask implements Runnable {

        @Override
        public void run() {
            // 切换图片
            currentItem = currentItem + 1;
            handler.sendEmptyMessage(0);
        }
    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {

            // 指定当前页面
            vViewpager.setCurrentItem(currentItem);
        };
    };
    private ImageView mRmb;

    @Override
    public void onResume() {
        super.onResume();
        showniuniu();
    }

}
